<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
    
    public $pageTitle = false;
    
    public $components = array(
        'Session', 
        'Auth' => array(
            'loginAction' => array(
                'controller' => 'app',
                'action'     => 'login'
            ),
            'authenticate' => array(
                'Form' => array(
                    'fields' => array(
                        'username' => 'email'
                    )
                )
            )
        )
    );
    
    public function beforeFilter() {
        parent::beforeFilter();
        
        $this->Auth->allow(array(
            'controller' => 'locations',
            'action'     => 'lista'
        ));
    }
    
    public function beforeRender() {
        parent::beforeRender();
        
        $this->set('title_for_layout', $this->pageTitle);
    }
    
    public function setFlash($message, $class='error') {
        $this->Session->setFlash($message, 'flash', array( 'class' => $class ));
    }
    
    protected function isAjax() {
        return !empty($this->params['named']['ajax']);
    }
    
    public function login() {
        $data = $this->data;
        
        if (! empty($data)) {
            if ($this->Auth->login()) {
                $this->redirect($this->Auth->redirectUrl());
            } else {
                $this->setFlash('Prijava nije uspela');
            }
        }
        
        $this->layout = 'login';
        $this->render('/Elements/login_form');
    }
    
    public function logout() {
        $this->redirect($this->Auth->logout());
    }
    
    public function saveData($modelName) {
        $data = $this->data;
        if (! empty($data)) {
            $this->$modelName->create($data);
            
            if (! $this->$modelName->validates()) {
                $this->setFlash('Uneti podaci nisu validni.');
                $this->set('data', $data);
                return $this->render('form');
            }
            
            if (! $this->$modelName->save($data)) {
                $this->setFlash('Greška pri čuvanju podataka.');
                $this->set('data', $data);
                return $this->render('form');
            }
            
            $this->setFlash('Sačuvano.', 'ok');
            $this->redirect('edit/' . $this->$modelName->id);
        }
        
        $this->redirect('index');
    }
    
    public function home() {
        $this->loadModel('Location');
        
        $locations = $this->Location->find('list', array(
            'order' => 'Location.name',
            'recursive' => false
        ));
        
        $this->set('locations', $locations);
        $this->render('/Elements/dashboard');
    }
    
    public function active_campaigns() {
        $this->loadModel('Campaign');
        $now = date('Y-m-d');
        $data = $this->Campaign->find('all', array(
            'fields' => array(
                'Campaign.id',
                'CampaignsLocation.start', 'CampaignsLocation.end',
                'Client.id', 'Client.name',
                'Location.name'
            ),
            'conditions' => array(
                'CampaignsLocation.start <=' => $now,
                'CampaignsLocation.end >='   => $now
            ),
            'joins' => array(
                array(
                    'table'      => 'campaigns_locations',
                    'alias'      => 'CampaignsLocation',
                    'type'       => 'INNER',
                    'conditions' => array('CampaignsLocation.campaign_id=Campaign.id')
                ),
                array(
                    'table'      => 'locations',
                    'alias'      => 'Location',
                    'type'       => 'INNER',
                    'conditions' => array('CampaignsLocation.location_id=Location.id')
                )
            ),
            'order' => 'CampaignsLocation.start DESC, CampaignsLocation.end DESC',
            'recursive' => false
        ));
        $this->set(compact('data'));
        $this->render('/Elements/active_campaigns', false);
    }
    
    public function expiring_campaigns() {
        $this->loadModel('Campaign');
    
        $first = date('Y-m-01');
        $last  = date('Y-m-d', strtotime(date('Y')."-".(intval(date('m'))+1)."-01") - 1);
        $data = $this->Campaign->find('all', array(
            'fields' => array(
                'Campaign.id',
                'CampaignsLocation.end',
                'Client.id', 'Client.name',
                'Location.name'
            ),
            'conditions' => array(
                'CampaignsLocation.end >=' => $first,
                'CampaignsLocation.end <=' => $last
            ),
            'joins' => array(
                array(
                    'table'      => 'campaigns_locations',
                    'alias'      => 'CampaignsLocation',
                    'type'       => 'INNER',
                    'conditions' => array('CampaignsLocation.campaign_id=Campaign.id')
                ),
                array(
                    'table'      => 'locations',
                    'alias'      => 'Location',
                    'type'       => 'INNER',
                    'conditions' => array('CampaignsLocation.location_id=Location.id')
                )
            ),
            'order' => 'CampaignsLocation.end DESC',
            'recursive' => false
        ));
        
        $this->set(compact('data'));
        $this->render('/Elements/expiring_campaigns', false);
    }
    
    protected function parseFilterData($modelName, $modifiers = array()) {
        $defaultSort = $this->$modelName->order;
        if (!empty($defaultSort)) {
            preg_match_all('/([^\s]+)\s?([ascde]*),?/i', $defaultSort, $matches);
            if (! empty($matches)) {
                $sort_by  = $matches[1][0];
                $sort_dir = $matches[2][0];
                if (empty($sort_dir)) {
                    $sort_dir = 'ASC';
                }
            }
        }
        
        if (empty($sort_by)) {
            $sort_by  = $modelName . '.id';
            $sort_dir = 'ASC';
        }
        if (! empty($this->params['named']['sort'])) {
            $sort_by = $this->params['named']['sort'];
        }
        if (! empty($this->params['named']['direction'])) {
            $sort_dir = $this->params['named']['direction'];
        }
        
        $filter = $this->data;
        $conditions = array();
        if (! empty($filter['Filter'])) {
            $filter = $filter['Filter'];
            foreach ($filter as $model=>$fields) {
                foreach ($fields as $field=>$value) {
                    $value = trim($value);
                    if (! empty($value)) {
                        if (empty($modifiers["{$model}.{$field}"])) {
                            $conditions["{$model}.{$field} LIKE"] = "%" . $value . "%";
                        } else {
                            $conditions = $modifiers["{$model}.{$field}"]($conditions, $value);
                        }
                    }
                }
            }
        }
        
        $return = new StdClass;
        $return->filter     = $filter;
        $return->sortBy     = $sort_by;
        $return->sortDir    = $sort_dir;
        $return->conditions = $conditions;
        
        return $return;
    }
    
    protected function setFilterData($filter) {
        $this->set('sort_by',  $filter->sortBy);
        $this->set('sort_dir', $filter->sortDir);
        $this->set('filter',   $filter->filter);
    }
}
